package com.jdk.demo.thread.semaphore;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo {

	public final static int SEM_SIZE = 10;

	public static void main(String[] args) throws InterruptedException {
		Semaphore semaphore = new Semaphore(SEM_SIZE);
		MyThread t1 = new MyThread("t1", semaphore);
		MyThread t2 = new MyThread("t2", semaphore);
		t1.start();
		Thread.sleep(100);
		t2.start();
		int permits = 5;
		System.out.println(Thread.currentThread().getName()+ " trying to acquire");
		try {
			semaphore.acquire(permits);
			System.out.println(Thread.currentThread().getName() + " acquire successfully");
			Thread.sleep(600000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			semaphore.release();
			System.out.println(Thread.currentThread().getName() + " release successfully");
		}

	}

}


class MyThread extends Thread {
    private Semaphore semaphore;
    private String name;

    public MyThread(String name, Semaphore semaphore) {
        super(name);
        this.name = name;
        this.semaphore = semaphore;
    }

    public void run() {
        int count = 3;
        System.out.println(Thread.currentThread().getName() + " trying to acquire");
        try {
        	Thread.sleep(10);
        	semaphore.acquire(count);
            System.out.println(Thread.currentThread().getName() + " acquire successfully");
            if(name.equals("t1"))
            	Thread.sleep(1000);
            else
            	Thread.sleep(600000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release(count);
            System.out.println(Thread.currentThread().getName() + " release successfully");
        }
    }
}